package com.zc.web.service.impl;

import com.zc.web.domain.AgeGroupStatistic;
import com.zc.web.domain.CategoryStatistic;
import com.zc.web.mapper.StatisticsMapper;
import com.zc.web.service.IStatisticService;
import com.zc.web.vo.StatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * ClassName:StatisticsServiceImpl
 * Description:
 * DateTime: 2025/10/23 10:09
 * Author: zc
 * Version: 1.0
 */
@Service
public class StatisticsServiceImpl implements IStatisticService {
    @Autowired
    private StatisticsMapper statisticsMapper;
    @Override
    public StatisticsVO getStatisticsOverview() {
        StatisticsVO statisticsVO = new StatisticsVO();
        statisticsVO.setUserCount(statisticsMapper.getUserCount());
        statisticsVO.setLifeEventCount(statisticsMapper.getLifeEventCount());
        statisticsVO.setTimeBookCount(statisticsMapper.getTimeBookCount());
        statisticsVO.setDailySentenceCount(statisticsMapper.getDailySentenceCount());
        return statisticsVO;
    }

    @Override
    public Map<String, Integer> getUserAgeStatistics() {
        List<AgeGroupStatistic> ageGroupList = statisticsMapper.getUserAgeGroupStatistics();

        Map<String, Integer> result = new LinkedHashMap<>();
        result.put("18-25岁", 0);
        result.put("26-30岁", 0);
        result.put("31-35岁", 0);
        result.put("36-40岁", 0);
        result.put("41-50岁", 0);
        result.put("50+岁", 0);

        for (AgeGroupStatistic stat : ageGroupList) {
            String ageGroup = getAgeGroup(stat.getAge());
            if (ageGroup != null) {
                result.put(ageGroup, result.getOrDefault(ageGroup, 0) + stat.getCount());
            }
        }

        return result;
    }

    @Override
    public Map<String,Integer> getTimeBookCategoryStatistics() {
        List<CategoryStatistic> categoryList = statisticsMapper.getTimeBookCategoryStatistics();
        LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
        for (CategoryStatistic category : categoryList) {
            result.put(category.getCategoryName(), category.getCount());
        }
        return result;
    }

    /**
     * 根据年龄确定所属年龄段
     */
    private String getAgeGroup(Integer age) {
        if (age == null) return null;
        if (age >= 18 && age <= 25) return "18-25岁";
        if (age >= 26 && age <= 30) return "26-30岁";
        if (age >= 31 && age <= 35) return "31-35岁";
        if (age >= 36 && age <= 40) return "36-40岁";
        if (age >= 41 && age <= 50) return "41-50岁";
        if (age > 50) return "50+岁";
        return null;
    }
}
